package com.ll.daipao.handler;


import com.ll.daipao.common.CommonFiles;
import com.ll.daipao.service.CoreService;
import com.ll.daipao.vo.City;
import com.ll.daipao.vo.TAccount;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by rockyll on 2017/10/12.
 */
public class UrlInterceptorHandler implements HandlerInterceptor {



    private  Logger logger = LoggerFactory.getLogger(UrlInterceptorHandler.class);
    @Autowired
    protected CoreService coreService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String url = httpServletRequest.getRequestURI();
        logger.info("----当前url：{}--- 当前参数：{}",url,httpServletRequest.getQueryString());
        List<String> igurls = CommonFiles.ignoredUrls();
        if(igurls!=null){
            for (String surl : igurls){
                if(url.contains(surl)){
                    return true;
                }
            }
        }
        String wx_openid = (String) httpServletRequest.getSession().getAttribute(Constants.WX_OPENID);
        if(StringUtils.isBlank(wx_openid)){
            httpServletResponse.sendRedirect(Constants.REAL_URL+"daipao/sigin");
            return false;
        }
        TAccount tAccount = (TAccount) httpServletRequest.getSession().getAttribute(Constants.WX_ACCOUNT);
        if(tAccount==null){
            tAccount =coreService.checkOpenId(wx_openid);
            httpServletRequest.getSession().setAttribute(Constants.WX_ACCOUNT,tAccount);
        }

        List<City> cities= (List<City>) httpServletRequest.getSession().getAttribute(Constants.WX_SCHOOL_INFO);
        if (cities==null||cities.size()<1) {
            cities = coreService.allSchool();
            httpServletRequest.getSession().setAttribute(Constants.WX_SCHOOL_INFO,cities);
        }
        //httpServletRequest.getSession().setAttribute(Constants.WX_OPENID,"12");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
